package com.zx.link.utils;

import java.util.Date;
import java.util.List;

import org.apache.commons.codec.binary.Base64;

import com.zx.link.entity.Link;
import com.zx.link.entity.LinkType;
/**
 * @Project: link
 * @Title: LinkToHtml
 * @Description: 转为html书签
 * @author: zhangxue
 * @date: 2017年3月4日下午8:48:54
 * @company: ......
 * @email: 1039791136@qq.com
 * @Copyright: Copyright (c) 2017
 * @version v1.0
 */
public class LinkToHtml {

	public static String toHTML(List<Link> linkList, List<LinkType> types){
		long datetime = new Date().getTime();
		StringBuffer html = new StringBuffer();
		html.append("<!DOCTYPE NETSCAPE-Bookmark-file-1>\r\n");
		html.append("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">\r\n");
		html.append("<TITLE>Bookmarks</TITLE>\r\n");
		html.append("<H1>Bookmarks</H1>\r\n");
		html.append("<DL>\r\n");
		html.append("<DT><H3 ADD_DATE="+datetime+" LAST_MODIFIED="+datetime+" PERSONAL_TOOLBAR_FOLDER=\"true\">书签栏</H3>\r\n");
		
		html.append("<DL>\r\n");
	
		for (LinkType type : types) {
			datetime++;
			html.append("<DT><H3 ADD_DATE="+datetime+" LAST_MODIFIED="+datetime+">"+type.getName()+"</H3>\r\n");
			html.append("<DL>\r\n");
			for (Link link : linkList) {
				if(type.getId().intValue() == link.getTid().intValue()) {
					datetime++;
					String a = toA(link, datetime);
					html.append("<DT>").append(a).append("</DT>\r\n");
				}
			}
			html.append("</DL>\r\n");
			html.append("</DT>\r\n");
		}
		html.append("</DL>\r\n");
		html.append("</DT>\r\n");
		html.append("</DL>\r\n");
		return html.toString();
	}
	
	
	private static String toA(Link link, long datetime){
		StringBuffer a = new StringBuffer();
		a.append("<A HREF=\"").append(link.getUrl()).append("\" ADD_DATE=\"").append(datetime).append("\" ");
		byte[] icon = link.getIcon();
		if(icon != null) {
			byte[] base64 = Base64.encodeBase64(icon);
			String string = new String(base64);
			a.append(" ICON=\"data:image/png;base64,").append(string).append("\"");
		} else {
			a.append(" ICON='' ");
		}
		a.append(">").append(link.getName()).append("</A>");
		return a.toString();
	}
}
